package com.zsc.shixun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsc.shixun.common.ResultCode;
import com.zsc.shixun.contant.Contant;
import com.zsc.shixun.controller.WebSocketServer;
import com.zsc.shixun.entity.Article;
import com.zsc.shixun.entity.CollectArticle;
import com.zsc.shixun.entity.CollectCategories;
import com.zsc.shixun.entity.User;
import com.zsc.shixun.exception.ApiException;
import com.zsc.shixun.mapper.CollectCategoriesMapper;
import com.zsc.shixun.model.collect.CollectCreateVO;
import com.zsc.shixun.model.collect.CollectMapping;
import com.zsc.shixun.model.collect.CollectUpdateVO;
import com.zsc.shixun.model.collect.CollectVO;
import com.zsc.shixun.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.shixun.utils.LoginMessageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 收藏夹类型表 服务实现类
 * </p>
 *
 * @author ZWYZY
 * @since 2020-06-06
 */
@Service
@Transactional
public class CollectCategoriesServiceImpl extends ServiceImpl<CollectCategoriesMapper, CollectCategories> implements ICollectCategoriesService {
    private static final Logger logger = LoggerFactory.getLogger(CollectCategoriesServiceImpl.class);
    @Autowired
    private IMessageService messageService;
    @Autowired
    private LoginMessageUtils loginMessageUtils;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CollectMapping collectMapping;

    @Autowired
    private ICollectArticleService collectArticleService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IArticleService articleService;

    @Override
    public List<CollectVO> getData(Long id) {
        if (redisTemplate.hasKey(Contant.COLLECT_KEY + id)) {
            return (List<CollectVO>) redisTemplate.opsForValue().get(Contant.COLLECT_KEY + id);
        }
        List<CollectCategories> collectCategoriesList = this.list(new QueryWrapper<CollectCategories>().lambda().eq(CollectCategories::getUserId, id));
        List<CollectVO> collectVOS = collectMapping.entitysToVos(collectCategoriesList);

        redisTemplate.opsForValue().set(Contant.COLLECT_KEY + id, collectVOS);
        return collectVOS;
    }

    @Override
    public void update(CollectUpdateVO collectUpdateVO) {
        CollectCategories collectCategories = new CollectCategories();
        BeanUtils.copyProperties(collectUpdateVO, collectCategories);
        try {
            this.updateById(collectCategories);
        } catch (Exception e) {
            logger.error("修改收藏夹类型失败");
            throw new ApiException(ResultCode.COLLECT_UPDATE_FAIL);
        }
        logger.info("修改收藏夹类型成功");
        if (redisTemplate.hasKey(Contant.COLLECT_KEY + collectCategories.getUserId())) {
            redisTemplate.delete(Contant.COLLECT_KEY + collectCategories.getUserId());
        }
    }

    @Override
    public void delete(Long id, Long uid) {
        try {
            this.removeById(id);
        } catch (Exception e) {
            logger.error("收藏夹类型删除失败");
            throw new ApiException(ResultCode.COLLECT_DELETE_FAIL);
        }
        logger.info("删除收藏夹类型成功");
        if (redisTemplate.hasKey(Contant.COLLECT_KEY + uid)) {
            redisTemplate.delete(Contant.COLLECT_KEY + uid);
        }
    }

    @Override
    public void insert(CollectCreateVO collectCreateVO, Long uid) {
        if (this.getOne(new QueryWrapper<CollectCategories>().lambda().eq(CollectCategories::getName, collectCreateVO.getName())) != null) {
            throw new ApiException(ResultCode.COLLECT_HAS_EXIST);
        }
        CollectCategories collectCategories = new CollectCategories();
        collectCreateVO.setUserId(uid);
        BeanUtils.copyProperties(collectCreateVO, collectCategories);
        try {
            this.save(collectCategories);
        } catch (Exception e) {
            logger.error("创建收藏夹类型失败");
            throw new ApiException(ResultCode.COLLECT_INSERT_FAIL);
        }
        logger.info("创建收藏夹类型成功");
        if (redisTemplate.hasKey(Contant.COLLECT_KEY + uid)) {
            redisTemplate.delete(Contant.COLLECT_KEY + uid);
        }
    }

    @Override
    public void collectArticle(Long aid, Long cid, Long uid) {
        CollectArticle collectArticle = new CollectArticle();
        collectArticle.setArticleId(aid);
        collectArticle.setCollectArticleId(cid);
        collectArticleService.save(collectArticle);

        CollectCategories collectCategories = this.getById(cid);
        collectCategories.setArticleNumber(collectCategories.getArticleNumber() + 1);
        this.updateById(collectCategories);

        User user = userService.getById(uid);
        user.setCollectNumber(user.getCollectNumber() + 1);
        userService.updateById(user);
        Article article=articleService.getById(aid);
        article.setCollectedNumber(article.getCollectedNumber()+1);
        articleService.updateById(article);
        logger.info("收藏文章成功");
        if (redisTemplate.hasKey(Contant.COLLECT_KEY + uid)) {
            redisTemplate.delete(Contant.COLLECT_KEY + uid);
        }
        String message = "博主名为" + loginMessageUtils.getMessage().getLoginUser().getUsername() + "的用户收藏了你的文章：" + article.getTitle();
        try {
            WebSocketServer.sendObjToUser(messageService.insertMessage(article.getUserId(), loginMessageUtils.getMessage().getLoginUser().getId(), message), article.getUserId());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
